package com.itheima.security;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyUserService implements UserDetailsService {
    //模拟数据库中的用户数据
    public  static Map<String, com.itheima.pojo.User> map = new HashMap<>();
    static {
        com.itheima.pojo.User user1 = new com.itheima.pojo.User();
        user1.setUsername("admin");
        user1.setPassword("$2a$10$kSa5lVQGBlaFZwIqPLxSG.nletIVWVE6PjIW6hq0kGp0ht0gaT4vi");

        com.itheima.pojo.User user2 = new com.itheima.pojo.User();
        user2.setUsername("xiaoming");
        user2.setPassword("$2a$10$kSa5lVQGBlaFZwIqPLxSG.nletIVWVE6PjIW6hq0kGp0ht0gaT4vi");

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("s = " + s);
        com.itheima.pojo.User user = map.get(s);
        if (user == null) {
            return null;
        }
        String password = user.getPassword();
        //根据用户id查询用户拥有的权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if(s.equals("admin")){
            authorities.add(new SimpleGrantedAuthority("checkitem_delete"));
        }
        authorities.add(new SimpleGrantedAuthority("checkitem_add"));

        return new User(s,password,authorities);
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        String encode = bc.encode("1234");
        System.out.println("bc = " + encode);
    }
}
